package com.example.bgxqwebsocket.service;

import com.example.bgxqapi.domain.dao.Message;
import com.example.bgxqapi.domain.dao.UserVerify;
import com.example.bgxqapi.domain.dto.UnreadUserMessage;
import com.example.bgxqapi.domain.result.UnreadMessageResult;
import com.example.bgxqapi.domain.send.AlreadyReadMessage;
import com.example.bgxqapi.domain.send.SendMessage;
import com.example.bgxqapi.domain.send.SendMessageType;
import com.example.bgxqapi.domain.send.WithdrawMessage;
import com.example.bgxqapi.exception.MissingParamException;
import com.example.bgxqapi.exception.NoPermissionException;
import com.example.bgxqapi.exception.ResourseNotExistException;
import com.example.bgxqapi.util.UserUtil;
import com.example.bgxqwebsocket.dao.MessageDao;
import com.example.bgxqwebsocket.dao.VerifyDao;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lizijian
 */
@Service
@Slf4j
public class MessageService {

  @Autowired
  private MessageDao messageDao;

  @Autowired
  private VerifyDao verifyDao;

  public int sendMessage(Message message) throws MissingParamException, NoPermissionException {
    if(message.getType()==2){
      /**
       * 如果消息类型是语音,时间字段不存在
       */
      if(message.getTime()==null){
        throw new MissingParamException("缺少time参数");
      }
      /**
       * 如果消息类型是语音,用户未实名认证
       */
      UserVerify userVerify = verifyDao.getVerifyByUserId(UserUtil.getUserId());
      if(userVerify==null||userVerify.getIsPassed()==0){
        throw new NoPermissionException("未实名认证,不可发送语音消息");
      }
    }
    messageDao.addMessage(message);
    return message.getId();
  }

  public void saveUnreadMessage(int messageId){
    messageDao.addUnreadMessage(messageId);
  }


  @Transactional(rollbackFor = Exception.class)
  public List<UnreadMessageResult> getUnreadMessage(int userId){
    List<UnreadUserMessage> unreadUserMessages = messageDao.getUnreadMessageByUserId(userId,
        UserUtil.getUserId());
    if(unreadUserMessages.size()>0){
      messageDao.deleteUnreadMessageByUserId(
          unreadUserMessages.stream().mapToInt(UnreadUserMessage::getId).toArray());
    }
    //给消息发送方发送已读提醒
    WebSocket.sendMessage(userId,new SendMessage<>(SendMessageType.ALREADY_READ.getName(),new AlreadyReadMessage(UserUtil.getUserId())));
    return unreadUserMessages.stream().map(UnreadMessageResult::new).collect(Collectors.toList());
  }

  public void withdraw(int id) throws ResourseNotExistException, NoPermissionException {
    Message message = messageDao.getMessageById(id);
    if(message==null){
      throw new ResourseNotExistException("聊天记录不存在");
    }
    if(message.getFromUserId()!=UserUtil.getUserId()){
      throw new NoPermissionException("不可撤回该消息");
    }
    WebSocket.sendMessage(message.getToUserId(),new SendMessage<>(SendMessageType.WITHDRAW.getName(),new WithdrawMessage(UserUtil.getUserId(),id)));
    messageDao.withdraw(id);
    messageDao.deleteMessage(id);
  }
}
